import {xhrSend, xhrOpen, isSupportSendBeacon} from "./common.js"
import generateUniqueID from './getUUID.js'
import { addCache, getCache, clearCache } from './cache.js'
import {config} from '../config.js'

// 判断是否支持 beacon
const sendBeacon = isSupportSendBeacon() ? window.navigator.sendBeacon.bind(window.navigator) : reportWithXHR
// 生成 sessionID
const sessionID = generateUniqueID()
/**
 * 上报数据
 * @param {Object} data 上报数据
 * @param {Boolean} isImmediate 是否立即上报，默认为 false
 * */
export function report(data, isImmediate = false) {
    if (!config.url) {
        console.error('请设置上传 url 地址')
    }

    const reportData = JSON.stringify({
        id: sessionID,
        ProjectName: config.projectName,
        appID: config.appId,
        userID: config.userId,
        data,
    })
    console.log(data);
    // if (isImmediate) {
    //     sendBeacon(config.url, reportData)
    //     return
    // }
    // if (window.requestIdleCallback) {
    //     window.requestIdleCallback(() => {
    //         sendBeacon(config.url, reportData)
    //     }, { timeout: 3000 })
    // } else {
    //     setTimeout(() => {
    //         sendBeacon(config.url, reportData)
    //     })
    // }
}


/**
 * 懒上报,每次相隔3s。
 * */
let timer = null
export function lazyReportCache(data, timeout = 3000) {
    addCache(data)
    clearTimeout(timer)
    timer = setTimeout(() => {
        const data = getCache()
        if (data.length) {
            report(data)
            clearCache()
        }
    }, timeout)
}
/**
 * XMLHttpRequest 上报数据
 * */
export function reportWithXHR(data) {
    const xhr = new XMLHttpRequest()
    xhrOpen.call(xhr, 'post', config.url)
    xhrSend.call(xhr, JSON.stringify(data))
}
